package com.ruoyi.project.system.service.impl;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.aspectj.DataScopeAspect;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.framework.security.service.TokenService;
import com.ruoyi.project.system.domain.*;
import com.ruoyi.project.system.mapper.SysRoleMenuMapper;
import com.ruoyi.project.system.mapper.SysTenantMapper;
import com.ruoyi.project.system.mapper.SysUserRoleMapper;
import com.ruoyi.project.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 租户Service业务层处理
 * 
 * @author ruoyi
 * @date 2020-03-26
 */
@Service
public class SysTenantServiceImpl extends ServiceImpl<SysTenantMapper, SysTenant> implements ISysTenantService
{
    @Autowired
    private SysTenantMapper sysTenantMapper;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private ISysRoleService roleService;
    @Autowired
    private ISysMenuService menuService;
    @Autowired
    private SysUserRoleMapper userRoleMapper;
    @Autowired
    private SysRoleMenuMapper roleMenuMapper;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ISysUserService userService;

    /**
     * 查询租户
     * 
     * @param id 租户ID
     * @return 租户
     */
    @Override
    public SysTenant selectSysTenantById(Long id)
    {
        return sysTenantMapper.selectSysTenantById(id);
    }

    /**
     * 查询租户列表
     * 
     * @param sysTenant 租户
     * @return 租户
     */
    @Override
    public List<SysTenant> selectSysTenantList(SysTenant sysTenant)
    {
        return sysTenantMapper.selectSysTenantList(sysTenant);
    }

    /**
     * 新增租户
     * 
     * @param sysTenant 租户
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map insertSysTenant(SysTenant sysTenant)
    {
        Map resMap= Maps.newHashMap();
        //保存租户的相关信息，并返回租户id,为租户随机生成一个六位的字符串
        sysTenant.setCreateTime(DateUtils.getNowDate());
        String code = RandomUtil.randomNumbers(6);
        sysTenant.setCode(code);
        sysTenantMapper.insert(sysTenant);
        Long tenantId=sysTenant.getId();
        // 以租户名为部门名称，创建用户的一级部门信息，并保存
        SysDept dept=new SysDept();
        dept.setDeptName(sysTenant.getName());
        dept.setPhone(sysTenant.getPhone());
        dept.setLeader(sysTenant.getContactPerson());
        dept.setEmail(sysTenant.getEmail());
        dept.setAncestors("0");
        dept.setParentId(0L);
        dept.setDelFlag("0");
        dept.setOrderNum("0");
        dept.setStatus("0");
        dept.setCreateBy(SecurityUtils.getUsername());
        dept.setCreateTime(DateUtils.getNowDate());
        dept.setTenantId(tenantId);
        deptService.save(dept);
        Long deptId = dept.getDeptId();
        // 为租户设置一个默认角色，角色名称“admin"
        SysRole sysRole=new SysRole();
        sysRole.setDataScope(DataScopeAspect.DATA_SCOPE_ALL);
        sysRole.setRoleName(sysTenant.getEnName()+"admin");
        sysRole.setRoleKey(sysTenant.getEnName()+"admin");
        sysRole.setTenantId(tenantId);
        sysRole.setRoleSort("0");
        sysRole.setDelFlag("0");
        sysRole.setStatus("0");
        sysRole.setCreateBy(SecurityUtils.getUsername());
        sysRole.setCreateTime(DateUtils.getNowDate());
        roleService.save(sysRole);
        Long roleId = sysRole.getRoleId();
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        //为租户新建一个登录用户
        SysUser sysUser=new SysUser();
        sysUser.setUserName(sysTenant.getEnName()+"admin");
        sysUser.setNickName(sysTenant.getEnName()+"admin");
        sysUser.setPhonenumber(sysTenant.getPhone());
        sysUser.setEmail(sysTenant.getEmail());
        sysUser.setDelFlag("0");
        sysUser.setPassword(SecurityUtils.encryptPassword(sysTenant.getEnName()+"admin"));
        sysUser.setDelFlag("0");
        sysUser.setDeptId(deptId);
        sysUser.setStatus("0");
        sysUser.setTenantId(tenantId);
        sysUser.setCreateBy(user.getUserName());
        sysUser.setCreateTime(DateUtils.getNowDate());
        userService.save(sysUser);
        Long userId1 = sysUser.getUserId();
        //保存用户的用户角色关系
        if (user !=null) {
            Long userId = user.getUserId();
            SysUserRole userRole=new SysUserRole();
            userRole.setRoleId(roleId);
            userRole.setUserId(userId1);
            userRoleMapper.insert(userRole);
            // 为用户预设的角色设置角色菜单对应关系
            List<SysRoleMenu> sysRoleMenus = roleMenuMapper.selectList(new LambdaQueryWrapper<SysRoleMenu>().eq(SysRoleMenu::getRoleId, 118));
            List<Long> menuIds =sysRoleMenus.stream().map(s ->s.getMenuId()).collect(Collectors.toList());
            menuIds.stream().forEach(s -> {
                SysRoleMenu roleMenu=new SysRoleMenu();
                roleMenu.setMenuId(s);
                roleMenu.setRoleId(roleId);
                int insert = roleMenuMapper.insert(roleMenu);
            });

        }
        resMap.put("userName",sysTenant.getName()+"admin");
        resMap.put("password",sysTenant.getName()+"admin");
        return resMap;
    }

    /**
     * 修改租户
     * 
     * @param sysTenant 租户
     * @return 结果
     */
    @Override
    public int updateSysTenant(SysTenant sysTenant)
    {
        sysTenant.setUpdateTime(DateUtils.getNowDate());
        return sysTenantMapper.updateSysTenant(sysTenant);
    }

    /**
     * 批量删除租户
     * 
     * @param ids 需要删除的租户ID
     * @return 结果
     */
    @Override
    public int deleteSysTenantByIds(Long[] ids)
    {
        return sysTenantMapper.deleteSysTenantByIds(ids);
    }

    /**
     * 删除租户信息
     * 
     * @param id 租户ID
     * @return 结果
     */
    @Override
    public int deleteSysTenantById(Long id)
    {
        return sysTenantMapper.deleteSysTenantById(id);
    }
}
